package com.ipinyou.optimus.kernel.zk;


import com.alibaba.fastjson.JSON;
import com.github.zkclient.exception.ZkMarshallingError;
import com.github.zkclient.serialize.ZkSerializer;

/**
 * 
 * Utility to serialize/deserialize data in ZK. <br/>
 * Using Json format 
 */
public class ZNRecordSerializer implements ZkSerializer {

	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ZNRecordSerializer.class);
	
    @Override
    public byte[] serialize(Object data) throws ZkMarshallingError {
        if (data != null) {
            String json = JSON.toJSONString(data, true);
            if (json != null) {
                return json.getBytes();
            }
        }
        return new byte[0];
    }

    @Override
    public Object deserialize(byte[] bytes) throws ZkMarshallingError {
        ZNRecord record = null;
        if (bytes != null) {
            try {
				record = JSON.parseObject(new String(bytes), ZNRecord.class);
				//正确的数据格式，可以解析正确，但不是正确的ZNRecord格式
				if(record.id ==null && record.listFields == null && record.mapFields == null){
					record.putSimpleField("err_parsed_raw_data_crnsnl", new String(bytes));
				}
			} catch (Exception e) {
				log.error("error : {}",bytes,e);
				record = new ZNRecord("err_parsed_raw_data_crnsnl");
				record.putSimpleField("err_parsed_raw_data_crnsnl", new String(bytes));
			}
        }
        return record;
    }

}
